//
//  testView.m
//  ezviz_plugin
//
//  Created by 柏柏柏柏柏 on 2021/4/7.
//

#import "TestFlutterPluginView.h"
#import <Flutter/Flutter.h>
#import <UIKit/UIKit.h>
#import <EZOpenSDKFramework/EZOpenSDKFramework.h>

@interface TestFlutterPluginView ()<EZPlayerDelegate>
/** channel*/
@property (nonatomic, strong) FlutterMethodChannel *channel;
@property (nonatomic, copy) NSString *appKey;
@property (nonatomic, copy) NSString *accessToken;
@property (nonatomic, copy) NSString *deviceSerial;
@property (nonatomic, strong) EZPlayer *player;
@property (nonatomic,strong) EZHCNetDeviceInfo *deviceInfo;
@property (nonatomic, strong) UIView *playerView;
@property (nonatomic, strong) UIButton *bgBtn;
@property (nonatomic,assign) NSInteger cameraNo;//通道号
@property (nonatomic, strong) NSTimer *playbackTimer;
@property (nonatomic, copy) NSString *url;
@end

@implementation TestFlutterPluginView
{
    CGRect _frame;
    int64_t _viewId;
    id _args;
    BOOL _isOpenSound;
    BOOL _isPlaying;
   
}


- (void)dealloc
{
    NSLog(@"%@ dealloc", self.class);
    [EZOpenSDK releasePlayer:_player];
    
}


- (id)initWithFrame:(CGRect)frame
  viewId:(int64_t)viewId
    args:(id)args
messager:(NSObject<FlutterBinaryMessenger>*)messenger
{
    if (self = [super init])
    {
        _frame = frame;
        _viewId = viewId;
        _args = args;
        _isOpenSound = YES;
        
        // !建立通信通道 用来 监听Flutter 的调用和 调用Fluttter 方法 这里的名称要和Flutter 端保持一致
        _channel = [FlutterMethodChannel methodChannelWithName:@"ezviz_plugin" binaryMessenger:messenger];
        // !建立通信通道 用来 监听Flutter 的调用和 调用Fluttter 方法 这里的名称要和Flutter 端保持一致
        
        __weak __typeof__(self) weakSelf = self;

        [_channel setMethodCallHandler:^(FlutterMethodCall * _Nonnull call, FlutterResult  _Nonnull result) {
            [weakSelf onMethodCall:call result:result];
        }];
    }
    
    
    self.playerView = [[UIView alloc] initWithFrame:frame];
    self.playerView.backgroundColor = [UIColor orangeColor];
    
    self.player = [EZOpenSDK createPlayerWithDeviceSerial:_deviceSerial cameraNo:_cameraNo];
    self.player.delegate = self;

    [self.player setPlayerView:self.playerView];
    [self.player startRealPlay];
    
    return self;
}

- (UIView *)view{
    return self.playerView;
}

#pragma mark -- Flutter 交互监听
-(void)onMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result{
    
    if ([call.method isEqual: @"getPlatformVersion"]) { //获取版本号
        result([@"iOS:" stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    }else if ([call.method isEqual: @"init"]) {// 初始化
//        NSString *appKey = call.arguments[@"appKey"];
//        NSLog(@"%@",appKey);
//        self.appKey = appKey;
//        //初始化SDK
//        [self initWithAppkey:appKey result:result];
        self.player = [EZPlayer createPlayerWithDeviceSerial:self.deviceSerial cameraNo:self.cameraNo];

        self.player.delegate = self;
        [self.player setPlayerView:self.playerView];
        [self.player startRealPlay];
       
        
    }else if ([call.method isEqualToString: @"startToPlay"]) { // 开始播放
        // 开始播放
        self.accessToken = call.arguments[@"accessToken"];
        self.deviceSerial = call.arguments[@"deviceSerial"];
        self.cameraNo = call.arguments[@"cameraNo"];
//        [self startRealPlay];
    }else if ([call.method isEqual: @"logout"]) { // 退出
        [EZOpenSDK logout:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }else if ([call.method isEqual: @"openSound"]) { //开始声音
        _isOpenSound = YES;
        [self voiceButtonClicked:_isOpenSound];
    }else if ([call.method isEqual: @"closeSound"]) { // 关闭声音
        _isOpenSound = NO;
        [self voiceButtonClicked:_isOpenSound];
    }else if ([call.method isEqual: @"pause"]) { //暂停
        _isPlaying = NO;
        [self playButtonClicked:_isPlaying];
    }else if ([call.method isEqual: @"resume"]) { // 回放
        _isPlaying = YES;
        [self playButtonClicked:_isPlaying];
    }else if ([call.method isEqual: @"release"]) { //释放播放器
        
        
    }else if ([call.method isEqual: @"setDirection"]) { //方向移动
        NSString * directionStr = call.arguments[@"direction"];
        int ivalue = [directionStr intValue];
        NSLog(@"你现在移动方向对应的编号:%d",ivalue);
        [self ptzStart:ivalue];
    }else{ //default
            
    }
}

// 初始化
-(void) initWithAppkey: (NSString *)appKey result: (FlutterResult) result {
//   /** * sdk日志开关，正式发布需要去掉 */
//    [EZOpenSDK setDebugLogEnable:YES];
//    /** * 设置是否支持P2P取流,详见api */
//    [EZOpenSDK enableP2P: NO];
//
//
//   /** * APP_KEY请替换成自己申请的 */
//    BOOL initResult = [EZOpenSDK initLibWithAppKey:appKey];
//    result(initResult? @"YES" : @"NO");
 }

#pragma mark - 按钮的点击事件action
- (void)ptzStart:(int)sender
{
    EZPTZCommandType command;

    switch (sender) {
        case 0:
            
            command = EZPTZCommandType_UP;
            break;
        case 1:
            command = EZPTZCommandType_DOWN;
            break;
        case 2:
            command = EZPTZCommandType_LEFT;
            break;
        case 3:
            command = EZPTZCommandType_RIGHT;
            break;
        default :
            break;;
    }
    
    [self ptzWithCommand:command action:EZPTZActionType_START];
}

//
- (void)ptzStop:(int)sender
{
    EZPTZCommandType command;
    
    switch (sender) {
        case 0:
            command = EZPTZCommandType_UP;
            break;
        case 1:
            command = EZPTZCommandType_DOWN;
            break;
        case 2:
            command = EZPTZCommandType_LEFT;
            break;
        case 3:
            command = EZPTZCommandType_RIGHT;
            break;
        default :
            break;
    }
    
    [self ptzWithCommand:command action:EZPTZActionType_STOP];
}

#pragma mark - PlayerDelegate Methods
//该方法废弃于v4.8.8版本，底层库不再支持。请使用getStreamFlow方法
- (void)player:(EZPlayer *)player didReceivedDataLength:(NSInteger)dataLength
{
    CGFloat value = dataLength/1024.0;
    NSString *fromatStr = @"%.1f KB/s";
    if (value > 1024)
    {
        value = value/1024;
        fromatStr = @"%.1f MB/s";
    }

//    [_emptyButton setTitle:[NSString stringWithFormat:fromatStr,value] forState:UIControlStateNormal];
}


- (void)player:(EZPlayer *)player didPlayFailed:(NSError *)error
{
    NSLog(@"player: %@, didPlayFailed: %@", player, error);
    //如果是需要验证码或者是验证码错误
    if (error.code == EZ_SDK_NEED_VALIDATECODE) {
        [self showSetPassword];
        return;
    } else if (error.code == EZ_SDK_VALIDATECODE_NOT_MATCH) {
        [self showRetry];
        return;
    } else if (error.code == EZ_SDK_NOT_SUPPORT_TALK) {
//        [UIView dd_showDetailMessage:[NSString stringWithFormat:@"%d", (int)error.code]];
//        [self.voiceHud hide:YES];
        return;
    }
    else
    {
        if ([player isEqual:_player])
        {
            [_player stopRealPlay];
        }
        else
        {
//            [_talkPlayer stopVoiceTalk];
        }
    }
}

- (void)player:(EZPlayer *)player didReceivedMessage:(NSInteger)messageCode
{
    NSLog(@"-----------------------------------------------> player: %@, didReceivedMessage: %d", player, (int)messageCode);
    if (messageCode == PLAYER_REALPLAY_START)
    {
        _isPlaying = YES;
        
        if (!_isOpenSound)
        {
            [_player closeSound];
        }
//        [self showStreamFetchType];
    }
    else if(messageCode == PLAYER_VOICE_TALK_START)
    {
        [_player closeSound];
    }
    else if (messageCode == PLAYER_VOICE_TALK_END)
    {
        //对讲结束开启声音
        if (_isOpenSound) {
            [_player openSound];
        }
    }
    else if (messageCode == PLAYER_NET_CHANGED)
    {
        [_player stopRealPlay];
        [_player startRealPlay];
    }
}
#pragma mark - support

//- (void) startRealPlay
//{
//    self.player = [EZPlayer createPlayerWithUserId:self.deviceInfo.userId cameraNo:self.cameraNo streamType:1];
//
//    if(_url) {
//        _player = [EZOpenSDK createPlayerWithUrl:_url];
//    }
//
//    self.player.delegate = self;
//    [self.player setPlayerView:_playerView];
//
//    [_player startRealPlay];
//    NSLog(@"----------------------->%d<-------------------------",[_player startRealPlay]);
//
//}

- (void) ptzWithCommand:(EZPTZCommandType) command action:(EZPTZActionType) action
{
    [EZHCNetDeviceSDK ptzControlWithUserId:self.deviceInfo.userId channelNo:self.cameraNo command:command action:action];
}

//- (void) showStreamFetchType
//{
//    int type = [self.player getStreamFetchType];
//
//    if (type >= 0)
//    {
//        self.streamTypeLabel.hidden = NO;
//        switch (type) {
//            case 0:
//                self.streamTypeLabel.text = @"取流方式：流媒体";
//                break;
//            case 1:
//                self.streamTypeLabel.text = @"取流方式：P2P";
//                break;
//            case 2:
//                self.streamTypeLabel.text = @"取流方式：内网直连";
//                break;
//            case 3:
//                self.streamTypeLabel.text = @"取流方式：外网直连";
//                break;
//            case 8:
//                self.streamTypeLabel.text = @"取流方式：反向直连";
//                break;
//            case 9:
//                self.streamTypeLabel.text = @"取流方式：NetSDK";
//                break;
//            default:
//                self.streamTypeLabel.text = @"取流方式：unknown";
//                break;
//        }
//    }
//}

//! 声音按钮的点击
- (void)voiceButtonClicked :(BOOL) openSound
{
    if(_isOpenSound){
        [_player closeSound];
    }
    else
    {
        [_player openSound];
    }
    _isOpenSound = !_isOpenSound;
}


- (void) invalidateTimer {
    if(self.playbackTimer)
    {
        [self.playbackTimer invalidate];
        self.playbackTimer = nil;
    }
}



// 播放按钮的点击
- (void)playButtonClicked: (BOOL) playing
{
    if(_isPlaying)
    {
        [_player pausePlayback];
        if(_playbackTimer)
        {
            [_playbackTimer invalidate];
            _playbackTimer = nil;
        }
    }
    else
    {
        [_player resumePlayback];
//        if(!_isSelectedDevice)
//            [self.loadingView startSquareClcokwiseAnimation];
            
    }
    _isPlaying = !_isPlaying;
}

- (void)showSetPassword
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"device_input_verify_code", @"请输入视频图片加密密码")
                                                        message:NSLocalizedString(@"device_verify_code_tip", @"您的视频已加密，请输入密码进行查看，初始密码为机身标签上的验证码，如果没有验证码，请输入ABCDEF（密码区分大小写)")
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"cancel", @"取消")
                                              otherButtonTitles:NSLocalizedString(@"done", @"确定"), nil];
    alertView.alertViewStyle = UIAlertViewStyleSecureTextInput;
    [alertView show];
}

- (void)showRetry
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"device_tip_title", @"温馨提示")
                                                        message:NSLocalizedString(@"device_verify_code_wrong", @"设备密码错误")
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"cancel", @"取消")
                                              otherButtonTitles:NSLocalizedString(@"retry", @"重试"), nil];
    [alertView show];
}

@end











